﻿using MangoMes.Commont.DapperHelps;
using MangoMes.Commont.DTOs;
using MangoMes.Commont.Infrastructures.Interfaces;
using MediatR;

namespace MangoMes.Write.API.Applications.Strippings
{
    public class RejectionsSeachHandler : IRequestHandler<RejectionsSeachCommand, PageDTO<RejectionsDto>>
    {
        #region 仓储
        /// <summary>
        /// 仓储
        /// </summary>
        private readonly IBateRepository<RejectionsDto> RejectionsDtoRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="RejectionsDtoRepository"></param>
        public RejectionsSeachHandler(IBateRepository<RejectionsDto> RejectionsDtoRepository)
        {
            this.RejectionsDtoRepository = RejectionsDtoRepository;
        }
        #endregion

        #region 生产退料单行 列表
        /// <summary>
        /// 生产退料单行 列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PageDTO<RejectionsDto>> Handle(RejectionsSeachCommand request, CancellationToken cancellationToken)
        {
            //异常处理
            try
            {
                //初始化一个ResultDTO<RejectionsDto>对象result，并设置Code为 0
                PageDTO<RejectionsDto> result = new PageDTO<RejectionsDto>();

                var pageNum = (request.pageIndex - 1) * request.pageSize;
                //创建DapperHelper对象 用于与数据库进行交互
                DapperHelper dapperHelper = new DapperHelper();
                RejectionsDto dto = new RejectionsDto();

                //连接mySql 
                //定义一个字符串变量conn 将dapperHelper对象的MangoMesWrite属性的值赋给它
                //用于辅助与数据库交互的工具类对象
                string conn = dapperHelper.MangoMesWrite;

                //sql语句
                string str = $"select * from rejections a join productmanage b on a.productManageNode=b.productManageNode join warehouselist c on a.StashId =c.StashId WHERE a.StrippingNode='{request.StrippingNode}'";

                var list = RejectionsDtoRepository.GetAll(str, dto, conn).ToList();

                result.TotalCount = list.Count();
                result.PageCount = (int)Math.Ceiling((list.Count() * 1.0) / request.pageSize);
                list = list.OrderBy(x => x.RejectionId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
                result.Data = list;

                return result;
            }
            catch (Exception)
            {

                throw;
            }
        }
        #endregion

    }
}
